package com.dcbeida.callback;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.view.Window;
import android.widget.Toast;


import java.lang.reflect.Type;

import dc.medicine.com.okhttplib.OkHttpUtils;
import dc.medicine.com.okhttplib.request.BaseRequest;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ================================================
 * <p>
 * ================================================
 */
public abstract class DialogCallback<T> extends JsonCallback<T> {

    private ProgressDialog dialog;

    private boolean isShow = true;

    private void initDialog(Activity activity, DialogInterface.OnCancelListener lis, String message) {
        dialog = new ProgressDialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(message);
        if (lis != null)
            dialog.setOnCancelListener(lis);
    }

    public DialogCallback(Activity activity, Class<T> clazz, DialogInterface.OnCancelListener lis) {
        super(clazz);
        initDialog(activity, lis, "请求网络中...");
    }

    public DialogCallback(Activity activity, Class<T> clazz, DialogInterface.OnCancelListener lis, String message) {
        super(clazz);
        initDialog(activity, lis, message);
    }

    public DialogCallback(Activity activity, Type type, DialogInterface.OnCancelListener lis) {
        super(type);
        initDialog(activity, lis, "请求网络中...");
    }

    public DialogCallback(Activity activity, Type type, DialogInterface.OnCancelListener lis, boolean isShow) {
        super(type);
        this.isShow = isShow;
        initDialog(activity, lis, "请求网络中...");
    }

    @Override
    public void onBefore(BaseRequest request) {
        super.onBefore(request);
        //网络请求前显示对话框
        if (dialog != null && !dialog.isShowing() && isShow) {
            dialog.show();
        }
    }

    @Override
    public void onAfter(boolean isFromCache, @Nullable T t) {
        super.onAfter(isFromCache, t);
        //网络请求结束后关闭对话框
        if (dialog != null && dialog.isShowing() && isShow) {
            dialog.dismiss();
        }
    }

    public void showError(String message){
        Toast.makeText(OkHttpUtils.getContext(), message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showError(final String message,int code,String data) {
        showError(message);
    }
}
